package com.zn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBUtil {
    static {
        try{
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("数据库驱动加载失败");
        }
    }
    //    final static 表示为常量
    private final static String url = "jdbc:mysql://121.196.166.117:3306/estoredbs?useSSL=false";
    private final static String user = "root";
    private final static String password = "jisuanji2022";
    /** 获取数据库连接 */
    public static Connection getConnection(){
        // 3.获取数据库连接
        Connection conn = null;
        try{
            conn=DriverManager.getConnection(url,user,password);
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("数据库连接异常");
        }
        return conn;
    }
    /** 关闭资源 */
    public static void closeResource(Connection conn, Statement stmt, ResultSet rs){
//        关闭结果集
        try {
            if(rs != null){
                if(!rs.isClosed()){
                    rs.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
//        关闭SQL操作对象
        try {
            if(stmt != null){
                if(!stmt.isClosed()){
                    stmt.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
//        关闭连接
        try{
            if(conn != null){
                if(!conn.isClosed()){
                    conn.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}